/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gesturetracking;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import javax.swing.JPanel;
import org.OpenNI.GeneralException;
import org.OpenNI.ImageGenerator;

/**
 *
 * @author xvanek9
 */
public class CameraPanel extends JPanel{
    
    private BufferedImage image;
    private int imWidth = 640, imHeight = 480;
    
    public CameraPanel(){
        this.setSize(imWidth, imHeight);
    }
    
     public void update(ImageGenerator imageGen)
  // get the latest Kinect camera image, and redraw
  {
    try {
      ByteBuffer imageBB = imageGen.getImageMap().createByteBuffer();
      image = bufToImage(imageBB);
      repaint();
    }
    catch (GeneralException e) {
      System.out.println(e);
    }

  }  // end of update()




  private BufferedImage bufToImage(ByteBuffer pixelsRGB)
  /* Transform the ByteBuffer of pixel data into a BufferedImage
     Converts RGB bytes to ARGB ints with no transparency.  */
  {
    int[] pixelInts = new int[imWidth * imHeight];
 
    int rowStart = 0;
        // rowStart will index the first byte (red) in each row;
        // starts with first row, and moves down
    int bbIdx;               // index into ByteBuffer
    int i = 0;               // index into pixels int[]
    int rowLen = imWidth * 3;    // number of bytes in each row
    for (int row = 0; row < imHeight; row++) {
	    bbIdx = rowStart;
      // System.out.println("bbIdx: " + bbIdx);
	    for (int col = 0; col < imWidth; col++) {
	      int pixR = pixelsRGB.get( bbIdx++ );
	      int pixG = pixelsRGB.get( bbIdx++ );
	      int pixB = pixelsRGB.get( bbIdx++ );
	      pixelInts[i++] = 
	         0xFF000000 | ((pixR & 0xFF) << 16) | 
	         ((pixG & 0xFF) << 8) | (pixB & 0xFF);
	    }
      rowStart += rowLen;   // move to next row
    }

    // create a BufferedImage from the pixel data
    BufferedImage im = 
	     new BufferedImage( imWidth, imHeight, BufferedImage.TYPE_INT_ARGB);
    im.setRGB( 0, 0, imWidth, imHeight, pixelInts, 0, imWidth );
    return im;
  }  // end of bufToImage()

  @Override
    public void paintComponent(Graphics g)
  // draw the scaled camera image and the message at the top-left
  { 
    super.paintComponent(g);
    if (image != null)
      g.drawImage(image, 0, 0, imWidth, imHeight, null);

  } // end of paintComponent()
  
}
